package eiisan.forkjointest.recursivetask;

import java.io.File;
import java.util.concurrent.RecursiveTask;

public class FileSizeTask extends RecursiveTask<Long> {
    private long sum;
    private File[] files;
    private FileSizeTask next;

    public FileSizeTask(File[] files) {
        this(files, null);
    }

    public FileSizeTask(File[] files, FileSizeTask next) {
        this.files = files;
        this.next = next;
    }

    public static long sumFiles(File[] files) {
        long size = 0L;
        for (File f : files) {
            if (!f.isDirectory()) {
                size += f.length();
            }
        }
        return size;
    }

    @Override
    protected Long compute() {
        FileSizeTask next = null;
        for (File f : files) {
            if (f.isDirectory()) {
                next = new FileSizeTask(f.listFiles(), next);
                next.fork();
            }
        }
        sum = sumFiles(files);
        while (next != null) {
            if (next.tryUnfork()) // directly calculate if not stolen
                sum += next.compute();
            else {
                sum += next.join();
            }
            next = next.next;
        }
        return sum;
    }

}
